package jp.co.worksap.ate.gomoku.localai;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import jp.co.worksap.ate.gomoku.model.GoPoint;
import jp.co.worksap.ate.gomoku.model.GoState;
import jp.co.worksap.ate.gomoku.model.Goban;
import jp.co.worksap.ate.gomoku.model.IGomokuAI;

public class SingleLevelAI implements IGomokuAI{

	@Override
	public GoPoint nextMove(Goban goban, GoState goType, int aiLevel) {
		List<GoNode> nodeList = LocalAIUtil.getAllValueableEmptyGoNode(goban, 2);
		GoState enemyType;
		if(goType == GoState.BLACK) {
			enemyType = GoState.WHITE;
		} else {
			enemyType = GoState.BLACK;
		}
		double max = 0.0;
		for(GoNode node : nodeList) {
			double attackScore = LocalAIUtil.computeGoScoreForOneSide(goban, goType, node.getX(), node.getY());
			double defendScore = LocalAIUtil.computeGoScoreForOneSide(goban, enemyType, node.getX(), node.getY());
			double score = attackScore + defendScore;
			node.setScore(score);
			if(score > max) {
				max = score;
			}
		}
		List<GoNode> maxList = new ArrayList<GoNode>();
		for(GoNode node : nodeList) {
			if(Math.abs(max - node.getScore())<0.0000001) {
				maxList.add(node);
			}
		}
		GoNode node;
		if(maxList.size()==1) {
			node = maxList.get(0);
		} else {
			Random r = new Random();
			node = maxList.get(r.nextInt(maxList.size()));
		}
		GoPoint resultPoint = new GoPoint(node.getX(), node.getY());
		return resultPoint;
	}

}
